package com.hnjfzn.file.service;

import java.io.InputStream;
import java.time.Duration;

import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.nacos.common.utils.IoUtils;
import com.hnjfzn.file.config.MinioConfig;
import com.hnjfzn.file.utils.FileUploadUtils;

/**
 * Minio 文件存储
 */
@Primary
@Service
public class MinioSysFileServiceImpl implements ISysFileService
{
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

    // 过期时间
    private static final long EXPIRY_TIME = 3600;

    /**
     * Minio文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        String fileName = FileUploadUtils.extractFilename(file);
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(inputStream, file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        IoUtils.closeQuietly(inputStream);
        return getUrl(fileName, null);
    }

    @Override
    public String getUrl(String key, Long expiryTime) throws Exception {
        // 设置过期时间，确保在 1 秒到 7 天之间
        long expiryInSeconds = null == expiryTime ? EXPIRY_TIME : expiryTime;
        // 1秒到7天之间
        expiryInSeconds = Math.max(1, Math.min(expiryInSeconds, 7 * 24 * 60 * 60));

        // 生成预签名 URL
        return client.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(minioConfig.getBucketName())
                        .object(key)
                        .expiry((int) expiryInSeconds)
                        .build()
        );
    }
}
